package com.beidouapp.security.mvc.view;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.view.AbstractView;

import com.beidouapp.security.mvc.exception.NoPdfFileViewException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * @author LAOT
 *
 */
public abstract class AbstractIText5PdfView extends AbstractView {
	private static final Log logger = LogFactory.getLog(AbstractIText5PdfView.class.getName());
	public AbstractIText5PdfView() {
		setContentType("application/pdf");
	}

	@Override
	protected boolean generatesDownloadContent() {
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected final void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// IE workaround: write into byte array first.
		ByteArrayOutputStream baos = createTemporaryOutputStream();

		// Apply preferences and build metadata.
		Document document = newDocument();
		PdfWriter writer = newWriter(document, baos);
		Map<String, Object> rMap=(Map<String, Object>) model.get("requestMap");
		if(null==rMap||(null!=rMap && null==rMap.get("tmpUUId"))){
			logger.error("tmpUUId为空，可能原因请求路径不对！");
			throw new NoPdfFileViewException("显示pdf文件路径有误！");
		}
		
		String tmpUUId=rMap.get("tmpUUId").toString();
		String fileName=tmpUUId+".pdf";
		String rootPath = request.getSession().getServletContext().getRealPath(File.separator); 
		String tmpDir=rootPath+"pdfFile"+File.separator;
		  File folder = new File(tmpDir);
		if(!folder.exists()){
			folder.mkdirs();
		}
		System.out.println("服务器根路径："+rootPath);
		//输出到服务器或本地
		newWriter(document, new FileOutputStream(tmpDir+fileName));
		prepareWriter(model, writer, request);
		buildPdfMetadata(model, document, request);
		// Build PDF document.
		document.open();
		buildPdfDocument(model, document, writer, request, response);
		document.close();
		// Flush to HTTP response.
		writeToResponse(response, baos);
		
	}

	protected Document newDocument() {
		return new Document();
	}

	protected PdfWriter newWriter(Document document, OutputStream os)
			throws DocumentException {
		return PdfWriter.getInstance(document, os);
	}

	protected void prepareWriter(Map<String, Object> model, PdfWriter writer,
			HttpServletRequest request) throws DocumentException {

		writer.setViewerPreferences(getViewerPreferences());
	}

	protected int getViewerPreferences() {
		return PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage;
	}

	protected void buildPdfMetadata(Map<String, Object> model,
			Document document, HttpServletRequest request) {
	}

	protected abstract void buildPdfDocument(Map<String, Object> model,
			Document document, PdfWriter writer, HttpServletRequest request,
			HttpServletResponse response) throws Exception;

}
